import 'package:flutter_clx_base/flutter_clx_base.dart';

class PermissionHelper {
  static VoidCallback defaultCall = () {};

  ///检查权限
  // 2023/2/16 权限适配ios
  // 2023/2/17 权限适配ios - 已完成
  static void request(
    List<Permission> permissionList, {
    VoidCallback? onSuccess,
    VoidCallback? onFailed,
    VoidCallback? onOpenSetting,
  }) async {
    PermissionStatus permissionStatus =
        await _requestPermission(permissionList);
    logger.d("---PermissionHelper---: permissionStatus=$permissionStatus");
    if (permissionStatus.isGranted) {
      // 权限通过
      onSuccess != null ? onSuccess() : defaultCall();
    } else if (permissionStatus.isDenied) {
      // 权限拒绝
      onFailed != null ? onFailed() : defaultCall();
    } else if (permissionStatus.isPermanentlyDenied) {
      //权限永久拒绝，且不在提示
      onOpenSetting != null ? onOpenSetting() : defaultCall();
    } else if (permissionStatus.isRestricted) {
      //IOS单独处理,跳转设置页即可,已支持
      onOpenSetting != null ? onOpenSetting() : defaultCall();
    } else if (permissionStatus.isLimited) {
      //IOS单独处理,跳转设置页即可,已支持
      onOpenSetting != null ? onOpenSetting() : defaultCall();
    }
  }

  //申请权限
  static Future<PermissionStatus> _requestPermission(
      List<Permission> permissionList) async {
    Map<Permission, PermissionStatus> statuses = await permissionList.request();
    PermissionStatus currentPermissionStatus = PermissionStatus.granted;
    statuses.forEach((key, value) {
      if (!value.isGranted) {
        currentPermissionStatus = value;
        return;
      }
    });
    return currentPermissionStatus;
  }

  //核对权限是否已获取
  static Future<bool> checkPermission(List<Permission> permissionList) async {
    for (var element in permissionList) {
      if (!await element.status.isGranted) {
        return false;
      }
    }
    return true;
  }
}
